<?php
require_once 'common/config.php';
require_once 'common/functions.php';

// 检查登录状态
check_login();

$db = db_connect();

// 获取课程ID
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (!$id) {
    redirect('courses.php', '无效的课程ID', 'error');
}

// 获取课程信息
$stmt = $db->prepare("SELECT * FROM courses WHERE id = ?");
$stmt->execute([$id]);
$course = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$course) {
    redirect('courses.php', '课程不存在', 'error');
}

// 获取课程分类
$categories = $db->query("SELECT * FROM course_categories WHERE status = 1")->fetchAll();

// 获取教练列表
$coaches = $db->query("SELECT * FROM coaches WHERE status = 1")->fetchAll();

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = trim($_POST['name']);
    $category_id = intval($_POST['category_id']);
    $coach_id = intval($_POST['coach_id']);
    $description = trim($_POST['description']);
    $capacity = intval($_POST['capacity']);
    $duration = intval($_POST['duration']);
    $price = floatval($_POST['price']);
    $course_date = $_POST['course_date'];
    $start_time = $_POST['start_time'];
    $end_time = $_POST['end_time'];
    $difficulty = intval($_POST['difficulty']);
    $status = isset($_POST['status']) ? 1 : 0;
    
    // 验证输入
    if (empty($name) || empty($description) || !$category_id || !$coach_id) {
        $error = '请填写所有必填项';
    } else {
        try {
            // 处理图片上传
            $cover_image = $course['cover_image'];
            if (!empty($_FILES['cover_image']['name'])) {
                $upload_dir = "../api/user/uploads/courses/";
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                $file_ext = strtolower(pathinfo($_FILES['cover_image']['name'], PATHINFO_EXTENSION));
                $file_name = uniqid() . '.' . $file_ext;
                $upload_path = $upload_dir . $file_name;
                
                if (move_uploaded_file($_FILES['cover_image']['tmp_name'], $upload_path)) {
                    // 删除旧图片
                    if ($cover_image && file_exists("../api/user/" . $cover_image)) {
                        unlink("../api/user/" . $cover_image);
                    }
                    $cover_image = 'uploads/courses/' . $file_name;
                } else {
                    throw new Exception('图片上传失败');
                }
            }
            
            // 更新数据库
            $stmt = $db->prepare("UPDATE courses SET 
                                name = ?, cover_image = ?, coach_id = ?, category_id = ?,
                                description = ?, capacity = ?, duration = ?, price = ?,
                                course_date = ?, start_time = ?, end_time = ?,
                                difficulty = ?, status = ?
                                WHERE id = ?");
                                
            $stmt->execute([$name, $cover_image, $coach_id, $category_id, $description,
                          $capacity, $duration, $price, $course_date, $start_time,
                          $end_time, $difficulty, $status, $id]);
            
            redirect('courses.php', '课程更新成功');
        } catch (Exception $e) {
            $error = '系统错误：' . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑课程 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
    .form-preview {
        margin-top: 10px;
    }
    .preview-image {
        max-width: 200px;
        max-height: 150px;
        object-fit: cover;
        border-radius: 4px;
    }
    .time-inputs {
        display: flex;
        gap: 10px;
        align-items: center;
    }
    .difficulty-options {
        display: flex;
        gap: 15px;
    }
    .difficulty-option {
        padding: 8px 15px;
        border: 1px solid #ddd;
        border-radius: 4px;
        cursor: pointer;
    }
    .difficulty-option.active {
        background: #007bff;
        color: white;
        border-color: #007bff;
    }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php include 'includes/sidebar.php'; ?>
        
        <div class="main-content">
            <header class="top-header">
                <div class="header-left">
                    <h2>编辑课程</h2>
                </div>
            </header>

            <div class="content">
                <div class="form-container">
                    <?php if (isset($error)): ?>
                    <div class="alert alert-danger">
                        <?php echo $error; ?>
                    </div>
                    <?php endif; ?>

                    <form method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="name">课程名称 <span class="required">*</span></label>
                            <input type="text" id="name" name="name" required 
                                   value="<?php echo htmlspecialchars($course['name']); ?>">
                        </div>

                        <div class="form-group">
                            <label for="category_id">课程分类 <span class="required">*</span></label>
                            <select id="category_id" name="category_id" required>
                                <option value="">请选择</option>
                                <?php foreach ($categories as $category): ?>
                                <option value="<?php echo $category['id']; ?>" 
                                        <?php echo $course['category_id'] == $category['id'] ? 'selected' : ''; ?>>
                                    <?php echo $category['name']; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="coach_id">授课教练 <span class="required">*</span></label>
                            <select id="coach_id" name="coach_id" required>
                                <option value="">请选择</option>
                                <?php foreach ($coaches as $coach): ?>
                                <option value="<?php echo $coach['id']; ?>" 
                                        <?php echo $course['coach_id'] == $coach['id'] ? 'selected' : ''; ?>>
                                    <?php echo $coach['name']; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="cover_image">课程封面</label>
                            <input type="file" id="cover_image" name="cover_image" accept="image/*">
                            <div class="form-preview">
                                <?php if ($course['cover_image']): ?>
                                <img src="../api/user/<?php echo htmlspecialchars($course['cover_image']); ?>" 
                                     class="preview-image" alt="当前封面">
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="description">课程描述 <span class="required">*</span></label>
                            <textarea id="description" name="description" rows="4" required><?php 
                                echo htmlspecialchars($course['description']); 
                            ?></textarea>
                        </div>

                        <div class="form-group">
                            <label for="capacity">课程容量 <span class="required">*</span></label>
                            <input type="number" id="capacity" name="capacity" min="1" required 
                                   value="<?php echo $course['capacity']; ?>">
                        </div>

                        <div class="form-group">
                            <label for="duration">课程时长(分钟) <span class="required">*</span></label>
                            <input type="number" id="duration" name="duration" min="15" step="15" required 
                                   value="<?php echo $course['duration']; ?>">
                        </div>

                        <div class="form-group">
                            <label for="price">课程价格 <span class="required">*</span></label>
                            <input type="number" id="price" name="price" min="0" step="0.01" required 
                                   value="<?php echo $course['price']; ?>">
                        </div>

                        <div class="form-group">
                            <label for="course_date">上课日期 <span class="required">*</span></label>
                            <input type="date" id="course_date" name="course_date" required 
                                   value="<?php echo $course['course_date']; ?>">
                        </div>

                        <div class="form-group">
                            <label>上课时间 <span class="required">*</span></label>
                            <div class="time-inputs">
                                <input type="time" name="start_time" required 
                                       value="<?php echo $course['start_time']; ?>">
                                <span>至</span>
                                <input type="time" name="end_time" required 
                                       value="<?php echo $course['end_time']; ?>">
                            </div>
                        </div>

                        <div class="form-group">
                            <label>难度等级 <span class="required">*</span></label>
                            <div class="difficulty-options">
                                <label class="difficulty-option">
                                    <input type="radio" name="difficulty" value="1" required hidden 
                                           <?php echo $course['difficulty'] == 1 ? 'checked' : ''; ?>>
                                    初级
                                </label>
                                <label class="difficulty-option">
                                    <input type="radio" name="difficulty" value="2" required hidden 
                                           <?php echo $course['difficulty'] == 2 ? 'checked' : ''; ?>>
                                    中级
                                </label>
                                <label class="difficulty-option">
                                    <input type="radio" name="difficulty" value="3" required hidden 
                                           <?php echo $course['difficulty'] == 3 ? 'checked' : ''; ?>>
                                    高级
                                </label>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="checkbox-label">
                                <input type="checkbox" name="status" value="1" 
                                       <?php echo $course['status'] ? 'checked' : ''; ?>>
                                <span>启用课程</span>
                            </label>
                        </div>

                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> 保存
                            </button>
                            <a href="courses.php" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> 返回
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
    // 图片预览
    document.getElementById('cover_image').onchange = function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = document.querySelector('.form-preview');
                preview.innerHTML = `<img src="${e.target.result}" class="preview-image">`;
            }
            reader.readAsDataURL(file);
        }
    };

    // 难度等级选择效果
    document.querySelectorAll('.difficulty-option').forEach(option => {
        option.addEventListener('click', function() {
            document.querySelectorAll('.difficulty-option').forEach(opt => opt.classList.remove('active'));
            this.classList.add('active');
            this.querySelector('input').checked = true;
        });

        if (option.querySelector('input').checked) {
            option.classList.add('active');
        }
    });
    </script>
</body>
</html> 